//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by Fernflower decompiler)
//

package org.itboys.weixin.tools;

import org.itboys.commons.utils.json.JsonUtils;
import org.itboys.weixin.dto.JsToken;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.MessageDigest;
import java.util.HashMap;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

public class WeixinJSUtils {
    protected Logger logger = LoggerFactory.getLogger(getClass());

    private static final Map<String, String> accessTokenMap = new HashMap();
    private static Timer timer = null;
    private static final String JSTICKET_URL = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?type=jsapi&access_token=";

    public WeixinJSUtils() {
    }

    public static String getJsTicket(String appId, String appKey) {
        String accessToken = (String)accessTokenMap.get(appId);
        if(accessToken != null) {
            return accessToken;
        } else {
            accessToken = WeixinUtils.getAccessToken(appId, appKey);
            String url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?type=jsapi&access_token=" + accessToken;
            String jsonToken = HttpHelper.doGet(url);

            System.out.println("-----WeixinJSUtils---jsonToken="+jsonToken);
            JsToken token = (JsToken) JsonUtils.jsonToObject(JsToken.class, jsonToken);
            accessTokenMap.put(appId, token.getTicket());
            if(timer == null) {
                timer = new Timer();
            }

            long delay = (long)token.getExpires_in().intValue();
            if(delay > 50L) {
                delay -= 50L;
            }

            timer.schedule(new WeixinJSUtils.ClearAccessTokenTask(appId), delay * 1000L);
            return token.getTicket();
        }
    }

    public static String checkSignature(String timestamp, String nonce, String url, String appId, String appKey) {
        String content = "jsapi_ticket=" + getJsTicket(appId, appKey) + "&noncestr=" + nonce + "&timestamp=" + timestamp + "&url=" + url;
        String tmpStr = null;

        try {
            MessageDigest e = MessageDigest.getInstance("SHA-1");
            e.reset();
            e.update(content.getBytes("UTF-8"));
            tmpStr = byteToStr(e.digest());
        } catch (Exception var8) {
            var8.printStackTrace();
        }

        return tmpStr;
    }

    private static String byteToStr(byte[] byteArray) {
        String strDigest = "";

        for(int i = 0; i < byteArray.length; ++i) {
            strDigest = strDigest + byteToHexStr(byteArray[i]);
        }

        return strDigest;
    }

    private static String byteToHexStr(byte mByte) {
        char[] Digit = new char[]{'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};
        char[] tempArr = new char[]{Digit[mByte >>> 4 & 15], Digit[mByte & 15]};
        String s = new String(tempArr);
        return s;
    }

    public static String getDownUrl(String mediaId, String appId, String appKey) {
        return "http://file.api.weixin.qq.com/cgi-bin/media/get?access_token=" + WeixinUtils.getAccessToken(appId, appKey) + "&media_id=" + mediaId;
    }

    public static boolean getRemoteFile(String strUrl, String fileName) throws IOException {
        URL url = new URL(strUrl);
        HttpURLConnection conn = (HttpURLConnection)url.openConnection();
        DataInputStream input = new DataInputStream(conn.getInputStream());
        DataOutputStream output = new DataOutputStream(new FileOutputStream(fileName));
        byte[] buffer = new byte[8192];
        boolean count = false;

        int count1;
        while((count1 = input.read(buffer)) > 0) {
            output.write(buffer, 0, count1);
        }

        output.close();
        input.close();
        return true;
    }

    static class ClearAccessTokenTask extends TimerTask {
        private String appId;

        public ClearAccessTokenTask(String appId) {
            this.appId = appId;
        }

        public void run() {
            synchronized(WeixinJSUtils.accessTokenMap) {
                WeixinJSUtils.accessTokenMap.remove(this.appId);
            }
        }
    }
}
